/*
 * @Author         : mli
 * @Email          : mli@poptown.io
 * @Description    : 
 * @FilePath       : /lib/common/json_converter.dart
 * @Date           : 2023-11-01 16:24:34
 * @LastEditTime: 2024-03-29 15:54:37
 * @LastEditors: mli mli@poptown.io
 */
import 'package:json_annotation/json_annotation.dart';
import '../extension/string_extension/string_validate.dart';

/// 自定义json序列化
/// 避免各个地方单独设置
/// 目前设置了:
/// 移除null字段, 而不是保留
class MyJsonSerializable extends JsonSerializable {
  const MyJsonSerializable(
      {super.genericArgumentFactories, super.includeIfNull = false});
}

/// 自动将不同类型的值转换为String类型
/// 一般是为了兼容int类型
class AnyToStringConverter implements JsonConverter<String, dynamic> {
  const AnyToStringConverter();

  @override
  String fromJson(json) => '$json';

  @override
  toJson(String object) => object;
}

class AnyToNullableStringConverter implements JsonConverter<String?, dynamic> {
  const AnyToNullableStringConverter();

  @override
  String? fromJson(json) => json != null ? '$json' : null;

  @override
  toJson(String? object) => object;
}

/// 自动将不同类型的值转换为int类型
/// 一般是为了兼容String类型
class AnyToIntConverter implements JsonConverter<int, dynamic> {
  const AnyToIntConverter();

  @override
  int fromJson(json) => int.tryParse('$json') ?? 0;

  @override
  toJson(int object) => object;
}

/// 将,分隔的字符串转换为字符串列表
class StringListConverter implements JsonConverter<List<String>, String> {
  const StringListConverter();

  @override
  List<String> fromJson(json) {
    if (json.trim().isEmpty) {
      return [];
    }
    return json.split(',').map((e) => e.trim()).toList();
  }

  @override
  toJson(List<String> object) => object.join(',');
}

/// 将不规范的换行符转换为规范的换行符
class ValidateNewLineConverter implements JsonConverter<String, String> {
  const ValidateNewLineConverter();

  @override
  String fromJson(json) => json.validateNewLine;

  @override
  toJson(String object) => object;
}

/// 消除前后的空格
class TrimConverter implements JsonConverter<String, String> {
  const TrimConverter();

  @override
  String fromJson(json) => json.trim();

  @override
  toJson(String object) => object;
}

/// 时间戳（毫秒）转换为DateTime
class DateTimeConverter implements JsonConverter<DateTime, int> {
  const DateTimeConverter();

  @override
  DateTime fromJson(json) => DateTime.fromMillisecondsSinceEpoch(json);

  @override
  toJson(DateTime object) => object.millisecondsSinceEpoch;
}

/// 毫秒转换为持续时间
class DurationConverter implements JsonConverter<Duration, int> {
  const DurationConverter();

  @override
  Duration fromJson(json) => Duration(milliseconds: json);

  @override
  toJson(Duration object) => object.inMilliseconds;
}
